﻿#region

using System.IO;
using Telerik.Web.Mvc.UI;

#endregion

namespace VinhSon.Areas.Administrator.Controllers
{
    public class ImageBrowserController : EditorFileBrowserController
    {
        private const string ContentFolderRoot = "~/Upload/";

        private const string PrettyName = "Images/";

        private static readonly string[] FoldersToCopy = new[] {"~/Content/Images"};

        /// <summary>
        ///     Gets the base paths from which content will be served.
        /// </summary>
        public override string[] ContentPaths
        {
            get
            {
                return new[] {CreateUserFolder()};
            }
        }

        private string CreateUserFolder()
        {
            string virtualPath = Path.Combine(ContentFolderRoot,
                                              PrettyName);
            string path = Server.MapPath(virtualPath);
            if(!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                foreach (string sourceFolder in FoldersToCopy)
                {
                    CopyFolder(Server.MapPath(sourceFolder),
                               path);
                }
            }
            return virtualPath;
        }

        private void CopyFolder(string source,
                                string destination)
        {
            if(!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            foreach (string file in Directory.EnumerateFiles(source))
            {
                string dest = Path.Combine(destination,
                                           Path.GetFileName(file));
                System.IO.File.Copy(file,
                                    dest);
            }
            foreach (string folder in Directory.EnumerateDirectories(source))
            {
                string dest = Path.Combine(destination,
                                           Path.GetFileName(folder));
                CopyFolder(folder,
                           dest);
            }
        }
    }
}
